
package io.renren.common.utils;

import lombok.SneakyThrows;
import org.apache.commons.codec.binary.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @version V1.0
 * @desc AES 加密工具类
 */
public class AESUtil {

    public enum Algorithm {
        PKCS5("AES/ECB/PKCS5Padding"), PKCS7("AES/ECB/PKCS7Padding"), CBCPKCS7("AES/CBC/PKCS7Padding");
        private String algorithm;

        Algorithm(String algorithm) {
            this.algorithm = algorithm;
        }

        public String getAlgorithm() {
            return algorithm;
        }

        public void setAlgorithm(String algorithm) {
            this.algorithm = algorithm;
        }
    }

    private static boolean initialized = false;
    private static final String KEY_ALGORITHM = "AES";
    private static byte[] iv = {0x30, 0x31, 0x30, 0x32, 0x30, 0x33, 0x30, 0x34, 0x30, 0x35, 0x30, 0x36, 0x30, 0x37, 0x30, 0x38};

    public static void initialize() {
        if (initialized) {
            return;
        }
        Security.addProvider(new BouncyCastleProvider());
        initialized = true;
    }

    /**
     * 生成加密秘钥
     *
     * @return
     */
    private static Key getSecretKey(byte[] keyBytes) {
        //返回生成指定算法密钥生成器的 KeyGenerator 对象
        KeyGenerator kg = null;
        try {
            kg = KeyGenerator.getInstance(KEY_ALGORITHM);
            SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
            random.setSeed(keyBytes);
            //AES 要求密钥长度为 128
            kg.init(128, random);
            //生成一个密钥
            SecretKey secretKey = kg.generateKey();
            // 转换为AES专用密钥
            return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(AESUtil.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static Key getKey(byte[] keyBytes) {
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyBytes.length % base != 0) {
            int groups = keyBytes.length / base + 1;
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyBytes, 0, temp, 0, keyBytes.length);
            keyBytes = temp;
        }
        // 转化成JAVA的密钥格式
        return new SecretKeySpec(keyBytes, KEY_ALGORITHM);
    }

    /**
     * 加密方法
     *
     * @param content  要加密的字符串
     * @param keyBytes 加密密钥
     * @return
     */
    @SneakyThrows
    public static byte[] encrypt(byte[] content, byte[] keyBytes, Algorithm algorithm) {
        byte[] encryptedText;
        Key key;
        Cipher cipher;
        initialize();
        if (algorithm.equals(Algorithm.PKCS5)) {
            key = getSecretKey(keyBytes);
            // 创建密码器
            cipher = Cipher.getInstance(algorithm.getAlgorithm());

        } else {
            key = getKey(keyBytes);
            cipher = Cipher.getInstance(algorithm.getAlgorithm(), "BC");
        }
        if (algorithm.equals(Algorithm.PKCS5) || algorithm.equals(Algorithm.PKCS7)) {
            cipher.init(Cipher.ENCRYPT_MODE, key);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));
        }
        encryptedText = cipher.doFinal(content);
        return encryptedText;
    }

    /**
     * 解密方法
     *
     * @param encryptedData 要解密的字符串
     * @param keyBytes      解密密钥
     * @return
     */
    @SneakyThrows
    public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, byte[] ivBytes, Algorithm algorithm) {
        byte[] encryptedText;
        Key key;
        Cipher cipher;
        initialize();
        if (algorithm.equals(Algorithm.PKCS5)) {
            key = getSecretKey(keyBytes);
            // 创建密码器
            cipher = Cipher.getInstance(algorithm.getAlgorithm());

        } else {
            key = getKey(keyBytes);
            cipher = Cipher.getInstance(algorithm.getAlgorithm(), "BC");
        }
        if (algorithm.equals(Algorithm.PKCS5) || algorithm.equals(Algorithm.PKCS7)) {
            cipher.init(Cipher.DECRYPT_MODE, key);
        } else {
            cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(ivBytes));
        }
        encryptedText = cipher.doFinal(encryptedData);
        return encryptedText;
    }

    public static byte[] decrypt(byte[] encryptedData, byte[] keyBytes, Algorithm algorithm) {
        return decrypt(encryptedData, keyBytes, iv, algorithm);
    }

    /**
     * @param str 要被加密的字符串
     * @param key 加/解密要用的长度为32的字节数组（256位）密钥
     * @return byte[]  加密后的字节数组
     */
    public static String encrypt(String str, String key, Algorithm algorithm) {
        try {
            byte[] bytes = encrypt(str.getBytes(StandardCharsets.UTF_8), key.getBytes(StandardCharsets.UTF_8), algorithm);
            return Base64.encodeBase64String(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encryptByPKCS5(String str, String key) {
        return encrypt(str, key, Algorithm.PKCS5);
    }

    public static String encryptByPKCS7(String str, String key) {
        return encrypt(str, key, Algorithm.PKCS7);
    }

    public static String encryptByCBCPKCS7(String str, String key) {
        return encrypt(str, key, Algorithm.CBCPKCS7);
    }

    /**
     * @param str 要被解密的字节数组
     * @param key 加/解密要用的长度为32的字节数组（256位）密钥
     * @return String  解密后的字符串
     */

    public static String decrypt(String str, String key, Algorithm algorithm) {
        try {
            byte[] bytes = Base64.decodeBase64(str);
            bytes = decrypt(bytes, key.getBytes(StandardCharsets.UTF_8), algorithm);
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decryptByPKCS5(String str, String key) {
        return decrypt(str, key, Algorithm.PKCS5);
    }

    public static String decryptByPKCS7(String str, String key) {
        return decrypt(str, key, Algorithm.PKCS7);
    }

    public static String decryptByCBCPKCS7(String str, String key) {
        return decrypt(str, key, Algorithm.CBCPKCS7);
    }


    public static String generateAESKey(int keySize) {
        try {
            KeyGenerator keyGen = KeyGenerator.getInstance("AES");
            keyGen.init(keySize); // 128, 192, or 256
            SecretKey secretKey = keyGen.generateKey();
            return java.util.Base64.getEncoder().encodeToString(secretKey.getEncoded());
        } catch (NoSuchAlgorithmException e) {

            return null;
        }
    }

    public static SecretKeySpec getSecretKeySpec(String base64Key) {
        byte[] decodedKey = java.util.Base64.getDecoder().decode(base64Key);
        return new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
    }
    public static void main(String[] args) throws Exception {
        String key = "vbm+05MqNMxV0yHclzEVbA==";
        //String baseStr = "df9bc4a24ddf45aba06a2a57f14ab10b1672348800000";
        String baseStr = "df9bc4a24ddf45aba06a2a57f14ab10b1736493029628";
        String en = encryptByPKCS5(baseStr, key);
        System.out.println(en);
        System.out.println("de：" + decryptByPKCS5(en, key));

        System.out.println(decryptByPKCS5("BvHulVWb+kboiMmLaKF9/I/Qq5dDTr3nXSv2IsSIkM5gNAatlWpn3cCvwp6AaF9+", key));
    }

}